/**
 * 患者我的收藏模块入口
 * Created by alice on 2016/7/12.
 */
require.config({
    baseUrl:'../js',
    paths:{
        "getData":"Util/getData",
        "config":"common/config",
        "components":"common/components",
        "common":"common/common",
        "jquery":"lib/jquery.min",
        "iscroll":"lib/iscroll",
        "pullToRefresh":"lib/pullToRefresh",
        "wx":"lib/jweixin-1.0.0"
    },
    shim : {
        "components": { deps : ["jquery"] }
    },
    urlArgs: "v=" + (new Date()).getTime()//以禁用浏览器缓存,上线后注释掉
});
require(['jquery','getData','config','common','components','iscroll','pullToRefresh','wx'],function($,getData,config,common,components,iscroll,pullToRefresh,wx){

    var refresher=pullToRefresh.refresher;
    var gm=common.gm;
    var getUuid=gm.para.get(window.location.href,"customerUuid");
    var token=gm.para.get(window.location.href,"token");
    /**
     * 无收藏 时跳转心灵 氧吧
     */
    $(".goto_refer_soul a").bind({
        touchend:function(){
            window.location.href="refer_soul.html?title=心灵氧吧&token="+token;
        }
    });
    /**分页功能**/
    var generatedCount = 1;
    var totalPage=0;
    //获取收藏信列表信息
    getData.getJson({
        page:"content",
        loading:true,
        inter:"getCommonCollectionList",
        data:{token:token,collectRule:1,pageNum:1,pageSize:20},
        callback:function(data){
            //服务器传输回应
            if(!data){
                components.alert("服务器出错!");
            }
            var getdata=data.value;
            if(getdata==undefined ||getdata==null ||getdata.length<=0){
                $(".empty_collection").show();
                return false;
            }
            var len=getdata.length;

            if(data.code=="2000"){
                var arr =getStrData(data);
                if(arr.length>0){
                    $("#dont_show").hide();
                }
                $(".alllive ul").html(arr.join(""));
                if(len>=20){
                    refresher.init({
                        id:"wrapper",//
                        pullDownAction:Refresh,
                        pullUpAction:Load
                    });
                    totalPage=data.total;
                    wrapper.refresh();
                }
                bindevent();
            }else{
                components.alert(data.message);
            }
        }
    });
    /**
     * 刷新
     * @constructor
     */
    function Refresh() {
        setTimeout(function () {	// <-- Simulate network congestion, remove setTimeout from production!
            var ____loading = new components.mask("loading");
            ____loading.show();
            refreshdata(20,1,function(data){
                ____loading.hide();
                $(".varioustype ul").html(getStrData(data).join(""));
                bindevent();
                generatedCount=1;
                totalPage=data.total;
                $(".pullUp").show();
                wrapper.refresh();
            });
        }, 1000);

    }

    /**
     * 加载
     * @constructor
     */
    function Load() {
        setTimeout(function () {// <-- Simulate network congestion, remove setTimeout from production!
            ++generatedCount;
            if(generatedCount<=totalPage)
                refreshdata(20,generatedCount,function(data){
                    $(".varioustype ul").append(getStrData(data).join(""));
                    bindevent();
                    if(generatedCount==data.total)
                        $(".pullUp").hide();
                    wrapper.refresh();
                });
            else
                $(".pullUp").hide();
        }, 1000);
    }
    /**
     * 收藏页面加载更多时调用
     * @param page 当前页面有多少条记录
     * @param pageno 当前第几页面
     * @param callback
     */
    function refreshdata(page,pageno,callbak){
        getData.getjsonp({
            page:"patient",
            inter:"getAllCustomerFavoriteList",
            data:{customerUuid:getUuid,pageCount:page,pageNo:pageno},
            callback:function(data){
                callbak && callbak(data);
            }
        });
    }
//分页功能结束


    function deleteCollect(obj,type){
        components.confirm("确定要删除吗？",function(){
            var collectType=obj.attr("favoritetype");
            var objid=obj.attr("contentuuid");
            gm.common.attention(token,1,collectType,objid,2,function(data){

                if(!data){
                    components.alert("服务器出错!");
                }
                if(data.code=="2000"){
                    components.alert({
                        "val" : "删除成功", "type" : "flash" , "callback" : function(){
                            obj.fadeOut(500);
                            obj.remove();
                            if($("ul li.isopen").length==0)
                                $(".empty_collection").show();
                        }
                    });
                }else{
                    components.alert(data.message);
                }
            });
        },function(){
            obj.children(".restore_left_slip").attr('data-box-status',0);
            obj.children(".restore_left_slip").css({"transform":"translate3d(0rem, 0px, 0px)"});
        });
        return false;
    }

    /**
     * 拼装html str,并返回arr
     * @param data
     */
    function getStrData(data){
        var arr = [];
        var tmp='<li class="isopen" favoriteUuid="{favoriteUuid}" contentUuid="{objId}" favoriteType="{collectType}" value="{url}">\
                    <div class="restore_left_slip asbg" data-box-status="0" style="transition: all 0.1s ease; transform: translate3d(0rem, 0px, 0px);">\
                        <div class="live">\
                            <img src="{image}">\
                        </div>\
                        <div class="text">\
                            <div class="collectionContentTitle"><p>{titleName}</p></div>\
                            <p class="time">\
                                {collectNum}{commonNum}\
                            </p>\
                        </div>\
					</div>\
				</li>';
        $(data.value).each(function(i,o){
            o.image=gm.common.isObjUsable(o.image)?window._interfaceImgPath+""+o.image:window.___defaultImage;
            //是否收藏
            var faritetype=o["collectType"];
            //是否收藏
            var isCollection=1;
            var title= o.titleName;
            var desc= o.titleName;
            var img= o.image;
            var favoriteType=faritetype;
            var contentUuid= o.objId;
            var collectRule=1;
            var str="isCollection="+isCollection+"&title="+title+"&desc="+desc+"&img="+img+"&contentType="+favoriteType+"&token="+token+"&favoriteUuid="+contentUuid+"&collectRule="+collectRule;
            if(faritetype==0){
                o.url='../doctor/informationfordetails.html?client=ios&contentUuid='+o["objId"]+"&"+str;
            }else if(faritetype==1){
                o.url='playing.html?client=ios&vidoUuid='+o["objId"]+"&"+str;
            }else
                components.alert("未知数据！");

            if(faritetype==0){
                var collectNum=gm.common.isObjUsable(o.collectNum);
                o.collectNum=collectNum?"<span style='margin-right: .5rem;'>收藏 "+o.collectNum+"</span>":"<span style='margin-right: .5rem;'>收藏 0</span>";//判断收藏字段是否存在
                o.commonNum= o.readNum?"<span style='margin-right: .5rem;'>阅读 "+o.readNum+"</span>":"<span style='margin-right: .5rem;'>阅读 0</span>";//判断阅读字段是否存在
            }else if(faritetype==1){
                var collectNum=gm.common.isObjUsable(o.collectNum);
                o.collectNum=collectNum?"<span style='margin-right: .5rem;'>收藏 "+o.collectNum+"</span>":"<span style='margin-right: .5rem;'>收藏 0</span>";//判断收藏字段是否存在
                var commonNum=gm.common.isObjUsable(o.commonNum);
                o.commonNum=commonNum?"<span style='margin-right: .5rem;'>评论 "+o.commonNum+"</span>":"<span style='margin-right: .5rem;'>评论 0</span>";//判断评论字段是否存在
            }

            arr.push(gm.replace(tmp,o));
        });
        return arr;
    }

    /**
     * 绑定事件
     */
    function bindevent(){
        //$(".alllive ul li > div:nth-child(1)").lrTouchMove();//初始化左滑

        $(".alllive ul li").bind({
            touchend:function(e){
                e.preventDefault();
            }
        });

        $(".alllive ul li").ontouch(function(){//页面跳转
            var url=$(this).attr("value");
            if(url!=undefined && url!=null && url!="")
                gm.pul.toUrl(url);
        },true);

        $(".ndh_del").ontouch(function(e){
            var obj = $(this).parent().parent();
            var type = "delete";
            deleteCollect(obj,type);
        },true);

    }

    setTimeout(function(){gm.common.setTitle(document.title);},200);
});